//
//  StockList.m
//  iHedron
//
//  Created by George Radev on 2011-07-22.
//  Copyright 2011 I Me Mine. All rights reserved.
//

#import "StockList.h"
#import "StockEdit.h"
#import "HedronCore.h"


@implementation StockList

@synthesize selectedRow;

#pragma mark -
#pragma mark View lifecycle


- (void)viewDidLoad {
    [super viewDidLoad];

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    //self.navigationItem.rightBarButtonItem = self.editButtonItem;
	self.title = @"Стока";
	
	UIBarButtonItem* rightButton = [[UIBarButtonItem alloc] initWithTitle:@"+" 
			style:UIBarButtonItemStyleDone target:self action:@selector(addNewStock)];
	self.navigationItem.rightBarButtonItem = rightButton;
	[rightButton release];
}


-(void)addNewStock{
	
	StockEdit *stockEdit = [[StockEdit alloc] initWithNibName:@"StockEdit" bundle:nil];		
	stockEdit.stockId = 0;
	stockEdit.stockName = @"Име на стока";
	[self.navigationController pushViewController:stockEdit animated:YES];
	[stockEdit release];
}


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
	[self.tableView reloadData];
}

/*
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}
*/
/*
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
}
*/
/*
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
}
*/

// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    return YES;
}



#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    return [[HedronCore getStocks] count];
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
    
    // Configure the cell...
	Stock* stock = (Stock*)([[HedronCore getStocks] objectAtIndex:indexPath.row]);
    cell.textLabel.text = stock.sname;
    return cell;
}


- (NSArray *) sectionIndexTitlesForTableView: (UITableView *) tableView {
	return [HedronCore getStocksIndex]; 
}

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
	long ix = [HedronCore getStockOffset: index];
	NSIndexPath* path = [NSIndexPath indexPathForRow:ix inSection:0];
	[tableView scrollToRowAtIndexPath:path atScrollPosition:UITableViewScrollPositionNone animated:YES];
	[path release];
	return ix; 
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/


/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source.
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
    }   
}
*/


/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/


/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/


#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	selectedRow = indexPath.row;
	
	Order* order = [HedronCore getCurrentEditableOrder];
	UIActionSheet *popupQuery;
	if(order){
		popupQuery = [[UIActionSheet alloc] 
					 initWithTitle: nil 
					 delegate:self 
					 cancelButtonTitle: @"Откажи"
					 destructiveButtonTitle: nil
					 otherButtonTitles:@"Добави към поръчката", @"Редактирай", @"Към редактираната поръчка",nil];
		[order release];
	}else{
		popupQuery = [[UIActionSheet alloc] 
					 initWithTitle: nil 
					 delegate:self 
					 cancelButtonTitle: @"Откажи"
					 destructiveButtonTitle: nil
					 otherButtonTitles:@"Добави към поръчката", @"Редактирай", nil];
	}	
	popupQuery.actionSheetStyle = UIActionSheetStyleBlackOpaque;
	[popupQuery showInView: self.view];
	[popupQuery release];
}

-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
	if (buttonIndex == 0) {
		//add to order
		NSArray* stocks = [HedronCore getStocks];
		Stock * selectedStock = (Stock*)[stocks objectAtIndex: selectedRow];
		Stock * orderStock = [[Stock alloc] init];
		
		orderStock.sid = selectedStock.sid;
		orderStock.sname = selectedStock.sname;
		orderStock.qty = 1;
		orderStock.price = 0;
		
		[[HedronCore getContextOrder] addStock:orderStock];
		
		[orderStock release];
		
	} else if (buttonIndex == 1) {
		//edit stock
		StockEdit *stockEdit = [[StockEdit alloc] initWithNibName:@"StockEdit" bundle:nil];	
		Stock * stock = (Stock*)[[HedronCore getStocks] objectAtIndex:selectedRow];
		stockEdit.stockId = stock.sid;
		stockEdit.stockName = stock.sname;
		[self.navigationController pushViewController:stockEdit animated:YES];
		[stockEdit release];
		
	} else if (buttonIndex == 2) {
		//add to edited stock
		Order* order = [HedronCore getCurrentEditableOrder];
		if(!order) return;
		
		NSArray* stocks = [HedronCore getStocks];
		Stock * selectedStock = (Stock*)[stocks objectAtIndex: selectedRow];
		Stock * orderStock = [[Stock alloc] init];
		
		orderStock.sid = selectedStock.sid;
		orderStock.sname = selectedStock.sname;
		orderStock.qty = 1;
		orderStock.price = 0;
		
		[order addStock:orderStock];
		
		[orderStock release];
		[order release];
	}
}



#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Relinquish ownership any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
    // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
    // For example: self.myOutlet = nil;
}


- (void)dealloc {
    [super dealloc];
}


@end

